package com.qf.utils;

import com.qf.dynamicdatasource.OrderNumberThreadLocal;
import com.qf.feign.api.ICarCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class OrderUtils {

    Integer dbNum = 2; // 两个库
    Integer tabNum = 2; // 两张表


    @Autowired
    private ICarCacheService carCacheService;

    public String getOrderId(Integer uid) {

        // 规则:时间+用户id后四位+流水号
        StringBuffer oidBuffer = new StringBuffer();

        // 1.时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        oidBuffer.append(date);

        // 2.用户id后四位
        String subUId = subUserId(uid.toString());
        oidBuffer.append(subUId);

        // 3.流水号
        String orderSequence = carCacheService.getOrderSequence();
        oidBuffer.append(orderSequence);

        return oidBuffer.toString();
    }

    public static void main(String[] args) {
        String uid = "1234567890";
  //      String s = subUserId(uid);
    //    System.out.println(s);
    }

    public  String subUserId(String uid) {

        StringBuffer buffer = new StringBuffer();
        // 1如果用户id超过四位，取后四位，
        // 如果用户id不够四位，要补0 ,10
        if (uid.length() < 4) {

            // 先添加之前的id
            buffer.append(uid);

            // 循环补0
            for(int i=0;i<(4-uid.length());i++){
                buffer.insert(0,0);
            }
        }else{
            buffer.append(uid.substring(uid.length()-4));
        }
        return buffer.toString();
    }

    public Integer setOrderDataSource(Integer uid) {

        // 1.获取用户id后四位
        Integer subUserId = Integer.parseInt(subUserId(uid.toString()));

        // 2.计算数据库的编号
        Integer dbIndex = (subUserId%dbNum)+1;

        // 3.设置数据源
        OrderNumberThreadLocal.set("db"+dbIndex);

        System.out.println("uid:"+uid);
        System.out.println("setOrderDataSource:db"+dbIndex);

        // 4、计算表的索引
        Integer tabIndex = (subUserId/tabNum%tabNum)+1;

        return tabIndex;
    }
}
